package com.local.web.config;

import com.local.web.interceptor.WebInterceptor;
import io.lettuce.core.ReadFrom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableAspectJAutoProxy //支持切面
public class WebConfig implements WebMvcConfigurer {

    @Value("${upload.image.save-path}")
    private String imageSavePath;

    /**
     * web拦截器
     */
    @Autowired
    private WebInterceptor webInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册web拦截器
        registry.addInterceptor(webInterceptor)
                .addPathPatterns("/user/**", "/cart", "/cart/**", "/order/**", "/coupon/**");
    }

    /**
     * 配置访问图片的虚拟目录，如：http://127.0.0.1:8091/images/goods/202210/20221029_1547263.jpg
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + this.imageSavePath);
//        registry.addResourceHandler("/goods/**").addResourceLocations("file:" + ProjectConfig.getFileUploadPath());
    }


    //@Bean //redis哨兵模式下的读写分离配置
    LettuceClientConfigurationBuilderCustomizer configurationBuilderCustomizer() {
        return new LettuceClientConfigurationBuilderCustomizer() {
            @Override
            public void customize(LettuceClientConfiguration.LettuceClientConfigurationBuilder clientConfigurationBuilder) {
                clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
            }
        };
    }
}
